package com.ja.inquiry.service.impl;

import com.ja.enumall.InquiryStatusEnum;
import com.ja.inquiry.pojo.*;
import com.ja.inquiry.service.InquiryService;
import com.ja.util.AllRecords;
import com.ja.util.ResultBuildVo;
import com.ja.util.ResultVo;
import com.ja.inquiry.mapper.InquiryMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by 11936 on 2019/4/28.
 */

@Service
public class InquiryServiceImpl implements InquiryService {
    @Autowired
    private InquiryMapper inquiryMapper;

    @Override
    public ResultVo search(InquirySelectVo inquirySelectVo) {
        int count = inquiryMapper.queryCount(inquirySelectVo);
        List<InquirySelectVo> list = inquiryMapper.queryPageBean(inquirySelectVo);
        for (InquirySelectVo in : list){
            in.setInquiryStatusName(InquiryStatusEnum.getStatusName(in.getInquiryStatus()));
        }
        AllRecords allRecords = new AllRecords();
        allRecords.setPageSize(inquirySelectVo.getPageSize());
        allRecords.resetTotalNumber(count);
        allRecords.setDataList(list);
        return ResultBuildVo.success(allRecords);
    }

    @Override
    public ResultVo selectMaterial(SpareSelectVo spareSelectVo) {
        int count = inquiryMapper.querySpareCount(spareSelectVo);
        List<Spare> list = inquiryMapper.selectMaterial(spareSelectVo);
        AllRecords allRecords = new AllRecords();
        allRecords.setPageSize(spareSelectVo.getPageSize());
        allRecords.resetTotalNumber(count);
        allRecords.setDataList(list);
        return ResultBuildVo.success(allRecords);
    }

    @Override
    @Transactional
    public ResultVo addInquiry(CreateInquiry createInquiry) {
        //备件集合
        List<SpareDetail> spareDetails = createInquiry.getInquiryDetailsList();
        //供应商集合
        List<SupplierDetail> supplierDetails = createInquiry.getSupplierDetailsList();
        //验证
        ResultVo resultVo5 = getResultVo(createInquiry, spareDetails, supplierDetails);
        if (resultVo5 != null) return resultVo5;


        //添加表头
        String requestForQuotationId = UUID.randomUUID().toString();
        createInquiry.setCreateTime(new Date());
        createInquiry.setRequestForQuotationId(requestForQuotationId);
        createInquiry.setLegalPersonCode(inquiryMapper.queryLegalPersonCode(createInquiry.getLegalPersonId()));
        inquiryMapper.addInquiry(createInquiry);

        //添加sparedetail表
        List<SpareDetail> spareDetailList = createInquiry.getInquiryDetailsList();
        for (SpareDetail spareDetail:spareDetailList){
            spareDetail.setRequestForQuotationId(requestForQuotationId);
            spareDetail.setType(createInquiry.getType());
        }
        inquiryMapper.addSpareDetailList(spareDetailList);

        //添加supplierdetail表
        List<SupplierDetail> supplierDetailList = createInquiry.getSupplierDetailsList();
        for (SupplierDetail supplierDetail:supplierDetailList){
            supplierDetail.setRequestForQuotationId(requestForQuotationId);
        }
        inquiryMapper.addSupplierDetailList(supplierDetailList);

        return ResultBuildVo.success(createInquiry);
    }

    private ResultVo getResultVo(CreateInquiry createInquiry, List<SpareDetail> spareDetails, List<SupplierDetail> supplierDetails) {
        //验证备件，供应商是否重复
        ResultVo resultVo = VerificationSpareRepeat(spareDetails, supplierDetails);
        if(!resultVo.isSuccess()){
            return resultVo;
        }

        //验证备件供应商是否存在
        ResultVo resultVo0= VerificationSpareRepeatExistence(spareDetails, supplierDetails);
        if(!resultVo0.isSuccess()){
            return resultVo0;
        }


        //验证备件是否存在生产它的供应商（如果没有可生产它的供应商，提示出来生产它的都有谁）

        ResultVo resultVo1 = VerificationSpareRelation(spareDetails, supplierDetails);
        if(!resultVo1.isSuccess()){
            return resultVo1;
        }
        //供应商是否存在它可以生产的备件（如果没有它可生产的备件，提示出来它可以生产都有谁）
        ResultVo resultVo2 = VerificationSupplierRelation(spareDetails, supplierDetails);
        if(!resultVo2.isSuccess()){
            return resultVo2;
        }
        //4.验证结束日期是否在开始日期之后、开始日期是否在结束日期之前。
        ResultVo resultVo3 = VerificationStartTimeRelation(createInquiry.getStartTime(), createInquiry.getEndTime());
        if(!resultVo3.isSuccess()){
            return resultVo3;
        }
        //5.法人是否存在、询价币别是否存在、询价类型是否存在.
        ResultVo resultVo4 = VerificationLegalPersonCurrencyTypeRelation(createInquiry.getLegalPersonId(), createInquiry.getType(),createInquiry.getCurrencyCode());
        if(!resultVo4.isSuccess()){
            return resultVo4;
        }
        return null;
    }

    private ResultVo VerificationLegalPersonCurrencyTypeRelation(Integer legalPersonCode, Integer type, String currencyCode) {
        String legalPersonCode1 = inquiryMapper.queryLegalPersonCode(legalPersonCode);
        if(legalPersonCode1 == null || legalPersonCode1.isEmpty()){
            return ResultBuildVo.error("法人为空","500");
        }

        return ResultBuildVo.success(null);
    }
    //验证日期
    private ResultVo VerificationStartTimeRelation(Date startTime, Date endTime) {
        Integer i=startTime.compareTo(endTime);
            if (i>0){
                return ResultBuildVo.error("开始日期在结束日期之后","500");
            }else if (i==0){
                return ResultBuildVo.error("开始日期和结束日期一致","500");
            }
        return ResultBuildVo.success(null);
    }
    //验证供应商是否重复
    private ResultVo VerificationSpareRepeat(List<SpareDetail> spareDetails, List<SupplierDetail> supplierDetails) {
        List<String> list = new ArrayList<>();
        List<String> listerror = new ArrayList<>();
        //遍历所有备件
        for (SpareDetail spareDetail:spareDetails){
            //如果list中包含了遍历备件中的某个备件，就提示此备件已经存在了，且提示出来。
            if(list.contains(spareDetail.getSpareCoding())){
                listerror.add(spareDetail.getSpareCoding());
            }
            //把遍历的每个备件放入list集合中
            list.add(spareDetail.getSpareCoding());
        }
        if (listerror.size()>0){
            return ResultBuildVo.success(listerror);
        }
        list.clear();
        listerror.clear();
        for (SupplierDetail supplierDetail:supplierDetails){
            if(list.contains(supplierDetail.getVendorCode())){
                listerror.add(supplierDetail.getVendorCode());
            }
            list.add(supplierDetail.getVendorCode());
        }
        if (listerror.size()>0){
            return ResultBuildVo.success(listerror);
        }
        return ResultBuildVo.success(null);
    }
    //验证备件是否重复
    private ResultVo VerificationSpareRepeatExistence(List<SpareDetail> spareDetails, List<SupplierDetail> supplierDetails) {
        //根据备件编码查询出这些备件的信息
        List<String> spareList = inquiryMapper.querySpareExistence(spareDetails);
        StringBuffer result = new StringBuffer();
        //用数据库查询出来的数量和前端传入的备件数量进行对比
        if (spareList.size() != spareDetails.size()){
            //找出不存在的备件，并且提示出来。
            for (SpareDetail spareDetail:spareDetails){
                if(!spareList.contains(spareDetail.getSpareCoding())){
                    return ResultBuildVo.error(spareDetail.getSpareCoding()+"备件不存在","500");
                }
            }
        }

        List<String> supplierList = inquiryMapper.querySupplierExistence(supplierDetails);
        if (supplierList.size() != supplierDetails.size()){
            for (SupplierDetail supplierDetail:supplierDetails){
                if(!supplierList.contains(supplierDetail.getVendorCode())){
                    return ResultBuildVo.error(supplierDetail.getVendorCode()+"备件不存在","500");
                }
            }
            result.append("供应商不存在，");
        }

        return ResultBuildVo.success(null);
    }
    //供应商是否存在它可以生产的备件（如果没有它可生产的备件，提示出来它可以生产都有谁）
    private ResultVo VerificationSupplierRelation(List<SpareDetail> spareDetails, List<SupplierDetail> supplierDetails) {
        //所以可以生产的beijian
        List<RelationVo> relationVos = inquiryMapper.querySupplierAll(supplierDetails);

        //分组
        Map<String, List<RelationVo>> groupBySex = relationVos.stream().collect(Collectors.groupingBy(RelationVo::getPartnerCode));
        //遍历分组
        for (Map.Entry<String, List<RelationVo>> relationVo : groupBySex.entrySet()) {
            String key = relationVo.getKey();
            List<RelationVo> entryByList = relationVo.getValue();
            for (SupplierDetail supplierDetails1 : supplierDetails
                 ) {
                if (key.equals(supplierDetails1)){
                    for (SpareDetail spareDetails1:spareDetails){
                        if(entryByList.contains(spareDetails1)){
                            return ResultBuildVo.success(spareDetails1.getSpareCoding());
                        } else{
                            return ResultBuildVo.success(entryByList);
                        }
                    }
                }

            }


        }
        return ResultBuildVo.success(null);
        }
    //备件是否存在可以生产它的供应商（如果没有可生产它的供应商，提示出来可以生产它供应商都有谁）
    private ResultVo VerificationSpareRelation(List<SpareDetail> spareDetails, List<SupplierDetail> supplierDetails) {
        //所以可以生产的供应商
        List<RelationVo> relationVos = inquiryMapper.querySpareAll(spareDetails);
        List<String> listAll = new ArrayList<>();
        //分组
        Map<String, List<RelationVo>> groupBySex = relationVos.stream().collect(Collectors.groupingBy(RelationVo::getSpareCoding));
        //遍历分组
        for (Map.Entry<String, List<RelationVo>> relationVo : groupBySex.entrySet()) {
            String key = relationVo.getKey();
            List<RelationVo> entryByList = relationVo.getValue();
            for (SpareDetail  spareDetails1: spareDetails
                 ) {
                if (key.equals(spareDetails1)){
                    for (SupplierDetail spareDetails2:supplierDetails){
                        if(entryByList.contains(spareDetails2.getVendorCode())){
                            return ResultBuildVo.success(spareDetails2.getVendorCode());
                        } else{
                            return ResultBuildVo.success(entryByList);
                        }
                    }
                }

            }


        }

        return ResultBuildVo.success(null);
    }

}
